package com.security.demo0928.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.security.demo0928.entity.Role;
import com.security.demo0928.entity.User;
import com.security.demo0928.service.RoleService;
import com.security.demo0928.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的登录接口
 * @date 2020/9/29 10:42
 */
@Service
public class CustomUserService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));

        if (StringUtils.isEmpty(user)) {
            System.out.println("用户不存在");
            return null;
        } else {

//            定义一个空的权限集合
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();

//        根据id查询出全部的权限
            List<Role> roles = roleService.list(new QueryWrapper<Role>().eq("role_user", user.getId()));

//        将id的权限的名字加到权限集合里面
            for (Role role : roles) {
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
            }
            return new org.springframework.security.core.userdetails.User(user.getUsername(),
                    user.getPassword(), authorities);
        }
    }
}

